﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using CommClass;


namespace DMS
{
    public partial class Frmcaigouyueku : DMS.FrmTemplate 
    {
       
        MO mo = new MO(App.Ds);
        CaigouDAO cg = new CaigouDAO(App.Ds);
        string sqlstr = "";
        int pageSize = App.pagesize;
        int currentPage = 0;
        int totalpage = 0;
        string orderBy = " CaigouNumber desc ";
        public Frmcaigouyueku()
        {
            InitializeComponent();
           
            this.chengyunshang();
            //this.getcmbsaletype();
            this.getgongyingshang();
            this.gethuozhu();
            this.getcangku();

            shouye.Enabled = false;
            shangye.Enabled = false;
            xiaye.Enabled = false;
            moye.Enabled = false;
            tiaozhuan.Enabled = false;
            textBox1.ReadOnly = true;
         
            
        }


        private void chengyunshang()
        {
            //承运商下拉
            DataTable dt = mo.GetCarrierID();
            DataRow dr = dt.NewRow();
            dr["CarrierID"] = "0";
            dr["CarrierName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            cmbcarrierid.DataSource = dt;
            cmbcarrierid.DisplayMember = "CarrierName";
            cmbcarrierid.ValueMember = "CarrierID";
            //默认选中
            cmbcarrierid.SelectedIndex = 0;

        }
      /*  private void getcmbsaletype()
        {
            //采购类型下拉
            DataTable dt = cg.getcaigoutype();
            DataRow dr = dt.NewRow();
            dr["CaigouTypeID"] = "0";
            dr["CaigouTypemiaoshu"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            cmbsaletype.DataSource = dt;
            cmbsaletype.DisplayMember = "CaigouTypemiaoshu";
            cmbsaletype.ValueMember = "CaigouTypeID";
            //默认选中
            cmbsaletype.SelectedIndex = 0;

        }**/

        private void getcangku()
        {
            //仓库下拉
            DataTable dt = mo.getcangku();
            DataRow dr = dt.NewRow();
            dr["StoreID"] = "0";
            dr["StoreName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            comboBox2.DataSource = dt;
            comboBox2.DisplayMember = "StoreName";
            comboBox2.ValueMember = "StoreID";
            //默认选中
            comboBox2.SelectedIndex = 0;

        }

        private void gethuozhu()
        {
            //货主下拉
            DataTable dt = mo.gethuozhu();
            DataRow dr = dt.NewRow();
            dr["SupplierID"] = "0";
            dr["SupplierName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "SupplierName";
            comboBox1.ValueMember = "SupplierID";
            //默认选中
            comboBox1.SelectedIndex = 0;

        }


        private void getgongyingshang()
        {
            //供应商下拉
            DataTable dt = mo.getgongyingshang();
            DataRow dr = dt.NewRow();
            dr["SupplySupplierID"] = "0";
            dr["SupplySupplierName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            comboBox3.DataSource = dt;
            comboBox3.DisplayMember = "SupplySupplierName";
            comboBox3.ValueMember = "SupplySupplierID";
            //默认选中
            comboBox3.SelectedIndex = 0;

        }
        private void getcheck()
        {
            StringBuilder strSql111 = new StringBuilder();
            strSql111.Append(" a.CaigouTypeID = " + App.yueku);
            //if (int.Parse(cmbsaletype.SelectedValue.ToString()) > 0)
           // {
          //      strSql111.Append(" and  a.CaigouTypeID =  " + cmbsaletype.SelectedValue.ToString());
           // }
            if (int.Parse(comboBox1.SelectedValue.ToString()) > 0)
            {
                strSql111.Append(" and  a.SupplierID =  " + comboBox1.SelectedValue.ToString());
            }
            if (int.Parse(comboBox2.SelectedValue.ToString()) > 0)
            {
                strSql111.Append(" and  a.StoreID =  " + comboBox2.SelectedValue.ToString());
            }
            if (int.Parse(cmbcarrierid.SelectedValue.ToString()) > 0)
            {
                strSql111.Append(" and  a.CarrierID =  " + cmbcarrierid.SelectedValue.ToString());
            }
            if (int.Parse(comboBox3.SelectedValue.ToString()) > 0)
            {
                strSql111.Append(" and  a.SupplySupplierID =  " + comboBox3.SelectedValue.ToString());
            }
           
            if (txtbOrderNumber.Text != null && txtbOrderNumber.Text.Trim() != "")
            {

                strSql111.Append(" and a.CaigouNumber  like  '%" + txtbOrderNumber.Text.Trim() + "%'");
            }
            if (txtbCustomer.Text != null && txtbCustomer.Text.Trim() != "")
            {

                strSql111.Append(" and a.CaigouID in ( select a.CaigouID from t_CaigouEntry a, t_Product b  where a.ProdID = b.ProdID  and b.ProdName  like  '%" + txtbCustomer.Text.Trim() + "%') ");
            }

            sqlstr = strSql111.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            currentPage = 0;
            this.getcheck();
            DataTable dt = cg.getCaigouData(pageSize, currentPage, sqlstr, orderBy);
            //给datagridview绑定数据
            dgvdo.DataSource = dt;
            if (this.dgvdo.ColumnCount > 0)
            {
                this.dgvdo.Columns[0].Visible = false;
                this.dgvdo.Columns[1].ReadOnly = true;
                this.dgvdo.Columns[1].DefaultCellStyle.BackColor = Color.AliceBlue;
                this.dgvdo.Columns[2].ReadOnly = true;
                this.dgvdo.Columns[3].ReadOnly = true;
                this.dgvdo.Columns[4].ReadOnly = true;
                this.dgvdo.Columns[5].ReadOnly = true;
                this.dgvdo.Columns[6].ReadOnly = true;
                this.dgvdo.Columns[7].ReadOnly = true;
                this.dgvdo.Columns[8].ReadOnly = true;
                this.dgvdo.Columns[9].ReadOnly = true;
                this.dgvdo.Columns[10].ReadOnly = true;
                this.dgvdo.Columns[10].DefaultCellStyle.BackColor = Color.AliceBlue;
                this.dgvdo.Columns[11].Visible = false;
            }
            int totalcount = cg.getCaigoucount(sqlstr);
            totalpage = (totalcount + pageSize - 1) / pageSize;
            zongye.Text = (currentPage+1) + "/" + totalpage;
            textBox1.Text = Convert.ToString(currentPage + 1);
            if (totalpage <= 1)
            {
                shouye.Enabled = false;
                shangye.Enabled = false;
                xiaye.Enabled = false;
                moye.Enabled = false;
                tiaozhuan.Enabled = false;
                textBox1.ReadOnly = true;
            }
            else
            {
                shouye.Enabled = false;
                shangye.Enabled = false;
                xiaye.Enabled = true;
                moye.Enabled = true;
                tiaozhuan.Enabled = true;
                textBox1.ReadOnly = false;
            }
       
        }
        private void shangye_Click(object sender, EventArgs e)
        {
            currentPage -= 1;
            DataTable dt = cg.getCaigouData(pageSize, currentPage, sqlstr, orderBy);
            this.dgvdo.DataSource = dt;
            zongye.Text = (currentPage + 1) + "/" + totalpage;
            textBox1.Text = Convert.ToString(currentPage + 1);
            if ((currentPage + 1) < totalpage)
            {
                xiaye.Enabled = true;
                moye.Enabled = true;
            }
            if (currentPage == 0)
            {
                shouye.Enabled = false;
                shangye.Enabled = false;
            }
        }
        private void shouye_Click(object sender, EventArgs e)
        {
            currentPage = 0;
            DataTable dt = cg.getCaigouData(pageSize, currentPage, sqlstr, orderBy);
            this.dgvdo.DataSource = dt;
            zongye.Text = (currentPage + 1) + "/" + totalpage;
            textBox1.Text = Convert.ToString(currentPage + 1);
            if ((currentPage + 1) < totalpage)
            {
                xiaye.Enabled = true;
                moye.Enabled = true;
            }
            shouye.Enabled = false;
            shangye.Enabled = false;
        }

        private void xiaye_Click(object sender, EventArgs e)
        {
            currentPage += 1;
            DataTable dt = cg.getCaigouData(pageSize, currentPage, sqlstr, orderBy);
            this.dgvdo.DataSource = dt;
            zongye.Text = (currentPage + 1) + "/" + totalpage;
            textBox1.Text = Convert.ToString(currentPage + 1);
            if ((currentPage + 1) < totalpage)
            {
                xiaye.Enabled = true;
                moye.Enabled = true;
            }
            else
            {
                xiaye.Enabled = false;
                moye.Enabled = false;
            }

            shouye.Enabled = true;
            shangye.Enabled = true;

        }

        private void moye_Click(object sender, EventArgs e)
        {
            currentPage = totalpage - 1;
            DataTable dt = cg.getCaigouData(pageSize, currentPage, sqlstr, orderBy);
            this.dgvdo.DataSource = dt;
            zongye.Text = (currentPage + 1) + "/" + totalpage;
            textBox1.Text = Convert.ToString(currentPage + 1);
            xiaye.Enabled = false;
            moye.Enabled = false;

            shouye.Enabled = true;
            shangye.Enabled = true;
        }

        private void tiaozhuan_Click(object sender, EventArgs e)
        {
            int corrent = 0;
            if (int.TryParse(textBox1.Text.ToString(), out corrent) && corrent > 0)
            {
                if (corrent <= totalpage)
                {
                    currentPage = corrent - 1;
                    DataTable dt = cg.getCaigouData(pageSize, currentPage, sqlstr, orderBy);
                    this.dgvdo.DataSource = dt;
                    zongye.Text = (currentPage + 1) + "/" + totalpage;
                    if (currentPage == 0)
                    {
                        shouye.Enabled = false;
                        shangye.Enabled = false;
                        xiaye.Enabled = true;
                        moye.Enabled = true;

                    }
                    else if ((currentPage + 1) == totalpage)
                    {
                        shouye.Enabled = true;
                        shangye.Enabled = true;
                        xiaye.Enabled = false;
                        moye.Enabled = false;
                    }
                    else
                    {

                        shouye.Enabled = true;
                        shangye.Enabled = true;
                        xiaye.Enabled = true;
                        moye.Enabled = true;
                    }
                }
                else
                {
                    textBox1.Text = Convert.ToString(currentPage + 1);
                    MessageBox.Show("页数过大");
                }
            }
            else
            {
                textBox1.Text = Convert.ToString(currentPage + 1);
                MessageBox.Show("页数必须是自然数");
            }
        }
      

             

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == -1 || e.RowIndex == -1) return;
            if (e.ColumnIndex == 10)
            {
                if (this.dgvdo.Rows[e.RowIndex].Cells["状态id"].Value.ToString() == Convert.ToString(App.newstatus))
                {
                    FrmAddInStork form = new FrmAddInStork(this.dgvdo.Rows[e.RowIndex].Cells[0].Value.ToString());
                    form.ShowDialog();
                    this.reflash111();
                }
                else
                {
                    MessageBox.Show("已关闭，不能修改");
                }
            }
            if (e.ColumnIndex == 1)
            {
                Frmviewyueku form = new Frmviewyueku(this.dgvdo.Rows[e.RowIndex].Cells[0].Value.ToString());
                form.ShowDialog();


            }
        }

      


        private void button6_Click_1(object sender, EventArgs e)
        {
            button6.Enabled = false;
          //查询需要越库的详情
            DataTable dt = cg.getYuekuData();
            if (dt.Rows.Count > 0)
            {
                //生成采购单
                using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
                {
                    conn.Open();
                    using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                    {
                        using (SqlCommand cmd = new SqlCommand())
                        {
                            cmd.Connection = conn;
                            cmd.Transaction = tran; //获取或设置将要其执行的事务  
                          // try
                          //  {
                                Caigou cgd = new Caigou();
                                InStock ins = new InStock();
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {
                                    
                                    //生成采购单
                                    if (i == 0 || (i > 0 && (dt.Rows[i]["SupplySupplierID"].ToString() != dt.Rows[i - 1]["SupplySupplierID"].ToString() || dt.Rows[i]["SupplierID"].ToString() != dt.Rows[i - 1]["SupplierID"].ToString())))
                                    {
                                   
                                    cgd.CaigouNumber = cgd.MakeCaigouNumber(conn, cmd);
                                    cgd.ZhiDanDate = DateTime.Now;
                                    cgd.CaigouDate = DateTime.Now;
                                    cgd.UserID = App.AppUser.UserID;
                                    cgd.CaigouTypeID = App.yueku;
                                    cgd.CaigouStatusID = App.guanbi;
                                    cgd.SupplierID = int.Parse(dt.Rows[i]["SupplierID"].ToString());
                                    cgd.SupplySupplierID = int.Parse(dt.Rows[i]["SupplySupplierID"].ToString());
                                    if (App.AppUser.CompanyID == null || App.AppUser.CompanyID == 0)
                                    {
                                        cgd.CarrierID = 1;
                                    }
                                    else
                                    {  
                                          cgd.CarrierID = App.AppUser.CompanyID;
                                    }
                                   
                                    cgd.CaigourenID = App.AppUser.UserID;
                                    cgd.StoreID = int.Parse(dt.Rows[i]["StoreID"].ToString());
                                    cgd.TuiHuoKeHu = "";
                                    cgd.TuiHuoRemark = "";
                                    cgd.Remark = "";
                                    cgd.CaigouID = cgd.saveCaigou(cgd, conn, cmd);
                                        //修改采购单状态为已经关闭

                                        //生成入库单
                                    //ins.InStockNumber;
                                    ins.CaigouNumber = cgd.CaigouNumber;
                                    ins.JieDanDate = DateTime.Now;
                                    ins.InStockDate = DateTime.Now;
                                    ins.UserID = App.AppUser.UserID;
                                    ins.InStockTypeID = App.newstatus;
                                    ins.InStockStatusID = App.newstatus;
                                    ins.SupplierID = cgd.SupplierID;
                                    ins.SupplySupplierID = cgd.SupplySupplierID;
                                    ins.CarrierID = cgd.CarrierID;
                                    //ins.ShouHuoID;
                                    ins.StoreID = cgd.StoreID;
                                    ins.TuiHuoKeHu = textBox1.Text;
                                    ins.TuiHuoRemark = "";
                                    ins.Remark = "";
                                     ins.InStockID = ins.saveInStock(ins, conn, cmd);
                                        //签核入库单
                                     ins.ShouHuoID = App.AppUser.UserID;
                                     ins.InStockStatusID = App.qianhestatus;
                                     ins.InStockDate = DateTime.Now;
                                     ins.updateInStockZhipai(ins, conn, cmd);
                                    }

                                    //插入明细
                                    CaigouEntry cae = new CaigouEntry();
                                    cae.CaigouID = cgd.CaigouID;
                                    cae.ProdID = int.Parse(dt.Rows[i]["ProdID"].ToString());

                                    double needqty = double.Parse(dt.Rows[i]["needqty"].ToString());

                                    double yifenpeiQty = double.Parse(dt.Rows[i]["yifenpeiQty"].ToString());

                                    double kucunqty = double.Parse(dt.Rows[i]["kucunqty"].ToString());

                                    double caigoushuliang = double.Parse(dt.Rows[i]["caigoushuliang"].ToString());

                                    cae.CaigouShuLiang = needqty - yifenpeiQty - kucunqty - caigoushuliang;
                                    cae.Caigoujia = double.Parse(dt.Rows[i]["caigoujia"].ToString());
                                    
                                    cae.Remark = "";
                                    cae.saveCaigouEntry(cae, conn, cmd);  
                                   
                                    //生成入库单
                                    InStockEntry inse = new InStockEntry();
                                    //inse.InStockEntryID;
                                    inse.InStockID = ins.InStockID;
                                    inse.ProdID = cae.ProdID;
                                    inse.ProdTypeID = int.Parse(dt.Rows[i]["ProdTypeID"].ToString());
                                    //inse.StorageID ;
                                    inse.Batch = DateTime.Now.ToString("yyyy-MM-dd");
                                    inse.ProduceDate = DateTime.Now;
                                    inse.StockPinZhiID = App.newstatus;
                                    inse.StockQtyYuBao = cae.CaigouShuLiang;
                                    // inse.StockQty;
                                    // inse.Remark;
                                    inse.InStockEntryID = inse.saveInStockEntry(inse, conn, cmd);
                                    //签核入库单
                                    inse.StockQty = cae.CaigouShuLiang;
                                    inse.StorageID = int.Parse(dt.Rows[i]["StorageID"].ToString());
                                    inse.updateInStockEntryHuowei(inse, conn, cmd);

                                    //增加库存
                                    Stock st = new Stock();
                                    st.ProdID = inse.ProdID;
                                    st.ProdTypeID = inse.ProdTypeID;
                                    st.SupplierID = ins.SupplierID;
                                    st.StorageID = inse.StorageID;
                                    st.Batch = inse.Batch;
                                    st.ProduceDate = inse.ProduceDate;
                                    st.InputDate = ins.InStockDate;
                                    st.StockPinZhiID = inse.StockPinZhiID;
                                    st.StockQty = Convert.ToDecimal(inse.StockQty);
                                    st.StockUseableQty =  Convert.ToDecimal(inse.StockQty) ;
                                    st.Remark = "";
                                    st.InStockNumber = Convert.ToString(inse.InStockEntryID);
                                    st.saveStock(st, conn, cmd);
                                }
                              

                                tran.Commit();
                                conn.Close();

                                MessageBox.Show("生成成功");
                           // }
                           // catch
                           // {

                          //      tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                           //     conn.Close();
                           //     MessageBox.Show("生成失败");
                           // }

                        }
                    }
                }
                button6.Enabled = true;
               // if (this.dgvdo.RowCount > 0)
               // {
                    this.reflash111();
               // }
            }
            else
            {
                MessageBox.Show("无需越库！");
            }
        }

        private void reflash111()
        {
            this.dgvdo.DataSource = cg.getCaigouData(pageSize, currentPage, sqlstr, orderBy);
        }
      
    }
}
